package com.ftwj.service;

import com.ftwj.dto.ApiResponse;
import com.ftwj.entity.UserAppointmentInfo;
import com.ftwj.mapper.SchoolRoomSeatMapper;
import com.ftwj.mapper.UserAppointmentInfoMapper;
import com.ftwj.utils.result.MessageEnum;
import com.ftwj.utils.result.ResultBean;
import com.ftwj.vo.UserAppointmentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class UserAppointmentInfoService {

    @Autowired
    private UserAppointmentInfoMapper userAppointmentInfoMapper;

    @Autowired
    private SchoolRoomSeatMapper schoolRoomSeatMapper;

    /**
     * 创建新的预约
     * @param userAppointmentInfo 预约信息
     */
    @Transactional
    public ApiResponse<Void> createAppointment(UserAppointmentInfo userAppointmentInfo) {
        // 检查结束时间是否有效
        if (!userAppointmentInfo.isEndTimeValid()) {
            return new ApiResponse<>(MessageEnum.BAD_REQUEST.getCode(), "结束时间必须大于开始时间半个小时以上");
        }

        // 检查是否有冲突的预约
        int conflictingAppointments = userAppointmentInfoMapper.countConflictingAppointments(
                userAppointmentInfo.getSeatId(),
                userAppointmentInfo.getStartTime(),
                userAppointmentInfo.getEndTime(),
                userAppointmentInfo.getId()
        );

        if (conflictingAppointments > 0) {
            return new ApiResponse<>(MessageEnum.BAD_REQUEST.getCode(), "该座位在选定的时间段内已被预约");
        }

        // 生成UUID
        if (userAppointmentInfo.getId() == null || userAppointmentInfo.getId().isEmpty()) {
            String newId = UUID.randomUUID().toString();
            userAppointmentInfo.setId(newId);
        }

        // 查询座位代码
        String seatCode = schoolRoomSeatMapper.findSeatCodeById(userAppointmentInfo.getSeatId());
        userAppointmentInfo.setSeatCode(seatCode);

        // 设置创建和更新时间
        Date now = new Date();
        userAppointmentInfo.setCreateTime(now);
        userAppointmentInfo.setUpdateTime(now);
        userAppointmentInfo.setState(1); // 1: 正常

        // 插入预约信息
        try {
            userAppointmentInfoMapper.insertAppointmentInfo(userAppointmentInfo);
            return new ApiResponse<>(MessageEnum.SUCCESS.getCode(), MessageEnum.SUCCESS.getMessage());
        } catch (Exception e) {
            return new ApiResponse<>(MessageEnum.INTERNAL_SERVER_ERROR.getCode(), MessageEnum.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    /**
     * 根据ID获取预约信息
     * @param id 预约ID
     * @return 预约信息
     */
    public UserAppointmentInfo getAppointmentById(String id) {
        return userAppointmentInfoMapper.findAppointmentInfoById(id);
    }

    /**
     * 更新预约信息
     * @param userAppointmentInfo 更新后的预约信息
     */
    @Transactional
    public void updateAppointment(UserAppointmentInfo userAppointmentInfo) {
        // 检查结束时间是否有效
        if (!userAppointmentInfo.isEndTimeValid()) {
            throw new IllegalArgumentException("结束时间必须大于开始时间半个小时以上");
        }
        // 设置更新时间
        userAppointmentInfo.setUpdateTime(new Date());
        userAppointmentInfoMapper.updateAppointmentInfo(userAppointmentInfo);
    }

    /**
     * 删除预约（逻辑删除）
     * @param id 预约ID
     */
    @Transactional
    public ResultBean deleteAppointment(String id) {
        UserAppointmentInfo userAppointmentInfo = userAppointmentInfoMapper.findAppointmentInfoById(id);
        if (userAppointmentInfo != null) {
            userAppointmentInfo.setState(-1);
            userAppointmentInfoMapper.updateAppointmentInfo(userAppointmentInfo);
            return new ResultBean(200, "预约单删除成功");
        } else {
            return new ResultBean(404, "预约单号为 " + id + " 的订单未找到");
        }
    }

    /**
     * 获取所有有效的预约信息
     * @return 预约信息列表
     */
    public List<UserAppointmentInfo> getAllAppointments(String userId) {
        return userAppointmentInfoMapper.findAllAppointmentInfo(userId);
    }

    /**
     * 定时任务：每分钟检查一次预约状态
     */
    @Scheduled(cron = "0 * * * * ?") // 每分钟执行一次
    @Transactional
    public void updateAppointmentStates() {
        // 获取当前时间
        java.util.Date now = new java.util.Date();

        // 更新状态为使用中
        userAppointmentInfoMapper.updateAppointmentStateToInUse(now);

        // 更新状态为已释放
        userAppointmentInfoMapper.updateAppointmentStateToReleased(now);
    }



    /**
     * 续约
     * @param appointmentId 预约ID
     * @param newEndTime 新的结束时间
     */
    @Transactional
    public void renewAppointment(String appointmentId, Date newEndTime) {
        // 获取当前预约信息
        UserAppointmentInfo currentAppointment = userAppointmentInfoMapper.findAppointmentInfoById(appointmentId);

        // 设置新的结束时间
        currentAppointment.setEndTime(newEndTime);

        // 确保结束时间至少延长半小时
        if (!currentAppointment.isEndTimeValid()) {
            throw new IllegalArgumentException("结束时间必须大于开始时间半个小时以上");
        }

        // 检查是否存在冲突的预约
        int conflictingAppointments = userAppointmentInfoMapper.countConflictingAppointments(
                currentAppointment.getSeatId(), currentAppointment.getStartTime(), currentAppointment.getEndTime(), currentAppointment.getId());

        if (conflictingAppointments > 0) {
            throw new IllegalArgumentException("该座位在选定的时间段内已被预约");
        }

        // 更新预约信息
        currentAppointment.setUpdateTime(new Date());
        userAppointmentInfoMapper.updateAppointmentInfo(currentAppointment);
    }

    /**
     * 手动更新预约状态
     * @param appointmentId 预约ID
     * @param newState 新的状态
     */
    @Transactional
    public void manuallyUpdateAppointmentState(String appointmentId, int newState) {
        UserAppointmentInfo appointment = userAppointmentInfoMapper.findAppointmentInfoById(appointmentId);
        if (appointment != null) {
            appointment.setAppointmentState(newState);
            appointment.setUpdateTime(new Date());
            userAppointmentInfoMapper.updateAppointmentInfo(appointment);
        } else {
            throw new IllegalArgumentException("预约ID无效");
        }
    }

}
